// pages/course/video/video.js
let app = getApp();
var WxParse = require('../../../wxParse/wxParse.js');
let utils = require('../../../utils/util.js')
const polyv = require('../../../utils/polyv.js')
const utilmd5 = require('../../../utils/md5.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    clientHeight: 0,
    currentTab: 0,
    videoInfo: null,
    handouts: "",
    cindex: -1,
    pindex: -1,
    url: "",
    cover:"-1"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.id = options.id;
    this.mtype = options.mtype;
    this.playDuration = options.playDuration;
    this.url = options.url;
    new app.WeToast();
    this.getDetail();

    app.event.on("buyvideo", this, res => {
      this.getDetail();
    })

    let that = this;
    wx.getSystemInfo({
      success: function (ret) {
        wx.createSelectorQuery().select('#top').boundingClientRect(function (rect) {
          that.setData({
            clientHeight: ret.windowHeight - rect.bottom
          });
        }).exec();
      }
    });

  },

  tabNav: function (e) {
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      var showMode = e.target.dataset.current == 0;
      this.setData({
        currentTab: e.target.dataset.current,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.videoContext = wx.createVideoContext('myvideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.addlog();
    app.event.remove("buyvideo", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getDetail() {
    app.httpUtils.postLoading(app.Api.GETVIDEOCOURSEDETAILS, {
      uid: app.globalData.userBean().id,
      id: this.id
    }).then(res => {
      if (res.code == '00') {
        var videoinfo = res.data;
        videoinfo.headPic = app.Api.getImageUrl(videoinfo.headPic);
        WxParse.wxParse('introduce', 'html', videoinfo.introduce, this)
        this.setData({
          videoInfo: videoinfo,
          cover: app.Api.getImageUrl(videoinfo.image)
        })
        //继续看视频
        if (this.mtype == '1') {
          this.buildPlay();
        }
      }
    })
  },

  /**
   * 继续播放
   */
  buildPlay() {
    var videoinfo = this.data.videoInfo;
    for (let i = 0; i < videoinfo.videoInfos.length; i++) {
      var mvideoInfo = videoinfo.videoInfos[i];
      for (let j = 0; j < mvideoInfo.children.length; j++) {
        var video = mvideoInfo.children[j];
        if (video.videoCourseId + "" === this.id + "") {
          var dethandouts = video.handouts;
          var text = dethandouts.replace(/<style(([\s\S])*?)<\/style>/g, "");
          WxParse.wxParse('handouts', 'html', text, this)
          this.setData({
            cindex: j,
            pindex: i,
            currentTab: 1,
            cover:""
            // url: this.url
          })
          //console.log(this.url);
          /*获取视频数据*/
          var that = this;
          var timestamp = Date.parse(new Date());
          console.log("当前时间戳是：" + timestamp);
          var secretKey = "U8Se01StXk";
          var ts = timestamp;
          var sign = utilmd5.hexMD5(secretKey+this.url+ts);
          polyv.getVideo(this.url, function (videoInfo) {
            that.setData({
              url: videoInfo.src[1]
            });
            setTimeout(res => {
              that.videoContext.seek(that.playDuration)
              that.videoContext.play();
            }, 500)
          },ts,sign);
          return
        }
      }
    }
  },

  /**
   *  视频事件更新
   */
  timeupdate(e) {
    this.currentPlayTime = e.detail.currentTime;
  },

  beginVideo(currenVideo) {
    app.httpUtils.postLoading(app.Api.BEGINWATCH, {
      uid: app.globalData.userBean().id,
      vid: currenVideo.id
    }).then(res => {
      if (res.code == '00') {
        var url = res.data.url;
        this.setData({
          cindex: this.cindex,
          pindex: this.pindex,
          currentTab: 1,
          // url: url
          cover: ""
        });

        /*获取视频数据*/
      var that = this;
      var timestamp = Date.parse(new Date());
      console.log("当前时间戳是：" + timestamp);
      var secretKey = "U8Se01StXk";
      var ts = timestamp;
      var sign = utilmd5.hexMD5(secretKey+url+ts);
      polyv.getVideo(url, function (videoInfo) {
          console.log(url)
          that.setData({
            url: videoInfo.src[1]
          });
          setTimeout(res => {
            that.videoContext.play()
          }, 500)
        },ts,sign);
      console.log("ts " + ts )
      console.log("sign " + sign)
      console.log("vid " + url )
        //获取默认讲义
        var dethandouts = currenVideo.handouts;
        var text = dethandouts.replace(/<style(([\s\S])*?)<\/style>/g, "");
        WxParse.wxParse('handouts', 'html', text, this)
        
      } else {
        this.wetoast.toast({
          title: res.msg,
          duration: 1000
        })
        if (res.code == '01') {
          wx.navigateTo({
            url: '../../buy/buy?vcid=' + this.data.videoInfo.id + "&type=2&courseInfoId=" + currenVideo.courseInfoId,
          })
        }
      }
    })
  },

  addlog() {
    if (this.data.cindex < 0 || this.currentPlayTime <= 0) return;
    var currenVideo = this.data.videoInfo.videoInfos[this.data.pindex].children[this.data.cindex];
    app.httpUtils.post(app.Api.ADDVIDEOLOG, {
      uid: app.globalData.userBean().id,
      vid: currenVideo.id,
      time: parseInt(this.currentPlayTime) + ""
    }).then(res => { })
  },

  lookVideo(e) {
    this.pindex = e.currentTarget.dataset.index;
    this.cindex = e.currentTarget.dataset.cindex;
    var currenVideo = this.data.videoInfo.videoInfos[this.pindex].children[this.cindex];
    console.log(currenVideo);
    this.beginVideo(currenVideo);
  }
})